package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomerException;
import com.itheima.dao.DishMapper;
import com.itheima.domian.Dish;
import com.itheima.domian.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    RedisTemplate redisTemplate;


    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //将菜品数据添加进去 操作菜品表
        this.save(dishDto);

        //将口味表的数据添加进去 操作口味表
        List<DishFlavor> flavors = dishDto.getFlavors();
        //获取口味对应的菜品id  两张表关联的主键
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        //将这个集合添加到对应的数据库表中
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品
        Dish byId = this.getById(id);
        //查询 口味
        List<DishFlavor> list = dishFlavorService.list(Wrappers.<DishFlavor>lambdaQuery().eq(DishFlavor::getDishId, id));
        //创建dto实体类将数据返回
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(byId, dishDto);
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //修改菜品的数据
        this.updateById(dishDto);
        //删除 口味表数据  然后在进行添加
        dishFlavorService.remove(Wrappers.<DishFlavor>lambdaQuery().eq(DishFlavor::getDishId, dishDto.getId()));
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(dishFlavor -> {
            dishFlavor.setDishId(dishDto.getId());
        });
        dishFlavorService.saveBatch(flavors);
    }

    //删除
    @Override
    public void delete(Long[] ids) {
        //判断该菜品是不是停售状态  否则不能删除
        int count = this.count(Wrappers.<Dish>lambdaQuery().eq(Dish::getStatus, 1).in(Dish::getId, ids));
        if (count > 0) {
            throw new CustomerException("不能删除正在启用的菜品");
        }

        //删除 对应的菜品
        this.remove(Wrappers.<Dish>lambdaQuery().in(Dish::getId, ids));
        //删除对应的口味表
        dishFlavorService.remove(Wrappers.<DishFlavor>lambdaQuery().in(DishFlavor::getDishId, ids));
        for (Long id : ids) {
            Dish dish = this.getById(id);
            String rediskey = dish.getCategoryId() + "Dishlist";
            redisTemplate.delete(rediskey);
        }
    }
}
